// miniprogram/pages/upload-pic.js

import {
  requst_uploadPic,
  requst_get_getPicInfo,
  requst_post_delPicInfo,
  requst_post_pareMpArticle,
  requst_post_saveMpArticleImages
} from '../../utils/api.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isUploading: false,
    picType: 0,
    current: 1,
    pageSize: 20,
    type: 1,
    isLastPage: false,
    showloadmore: true,
    posts: [], //壁纸
  },

  /**
   * 生命周期函数--监听页面加载
   * options.type 1 --上传壁纸 
   */


  onLoad: function (options) {
    let title;
    this.setData({
      type: options.type,
    })
    if (options.type == 1) {
      title = '壁纸上传'
      this.getPicList()

    } else if (options.type == 2) {
      title = '头像上传'
      this.getPicList()

    }
    wx.setNavigationBarTitle({
      title: title,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  onShareAppMessage: function () {
    var title;
    if (this.data.type == 3) { //渣男壁纸
      title = "咚，好友分享你一组渣男壁纸、请查收！"
    } else { //动漫壁纸
      title = "咚，好友分享你一组动漫壁纸、请查收！"
    }

    return {
      title: title,
      path: "/pages/upload-pic/upload-pic?type=" + this.data.type

    };
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  onPullDownRefresh: function () {
    var that = this
    that.setData({
      current: 1,
      isLastPage: false,
      showloadmore: true,
      posts: [], //壁纸
    })
    this.getPicList()
  },
  tabselect: function (t) {
    this.setData({
      picType: t.currentTarget.dataset.pictype,
      current: 1,
      isLastPage: false,
      isUploading: false,
      showloadmore: true,
      posts: []
    })
    this.getPicList()
  },
  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },
  //解析公众号图片
  pareMpArticle: function () {
    var that = this;
    const params = {
      mpUrl: this.data.inputValue,
    }
    requst_post_pareMpArticle(params).then(res => {
      var picList = [];
      for (let index = 0; index < res.data.picList.length; index++) {
        var picInfo = {};
        const element = res.data.picList[index];
        picInfo['path'] = element
        picInfo['picStatus'] = 0
        picList.push(picInfo)
      }
      that.setData({
        title:res.data.title,
        mpName:res.data.mpName,
        posts: [],
        isUploading: true,
        ispareMoudle: true
      })
      that.setData({
        posts: that.data.posts.concat(picList)
      })
    }).catch(err => {})
  },
  getPicList: function () {
    if (this.data.isUploading) {
      return;
    }
    var that = this;
    const params = {

      current: that.data.current,
      size: that.data.pageSize
    }
    if (this.data.type == 1) {
      params['picCategory'] = 1,
        params['groupId'] = that.data.picType
    } else if (this.data.type == 2) {
      params['picCategory'] = 2
    }

    requst_get_getPicInfo(params).then(res => {
      if (that.data.current == res.data.pages) {
        that.setData({
          isLastPage1: true,
        })
      }
      that.setData({
        posts: that.data.posts.concat(res.data.records)
      })
      wx.stopPullDownRefresh();
    }).catch(err => {
      wx.stopPullDownRefresh();
    })
  },

  onReachBottom: function () {
    let that = this;
    this.setData({
      current: this.data.current + 1,
    })
    if (!this.data.isLastPage) {
      this.getPicList()
    }
  },

  /**上传图片 */
  uploadImage: function () {
    let that = this;
    wx.chooseMedia({
      count: 20,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success(res) {
        var picList = [];
        for (let index = 0; index < res.tempFiles.length; index++) {
          var picInfo = {};
          const element = res.tempFiles[index];
          picInfo['path'] = element.tempFilePath
          picInfo['picStatus'] = 0
          picList.push(picInfo)
        }
        that.setData({
          posts: [],
          isUploading: true
        })
        that.setData({
          posts: that.data.posts.concat(picList)
        })

      }
    })
  },
  delFile: function (t) {
    console.log(t.currentTarget.dataset.index)
     var that = this;
    if (this.data.isUploading&&this.data.ispareMoudle) {
          this.data.posts.splice(t.currentTarget.dataset.index, 1)
          this.setData({
            posts: this.data.posts
          })
    }else if(this.data.isUploading){
      wx.showToast({
        title: '上传模式不支持删除',
        icon: 'none'
      })
      return;
    }
    if (!this.data.isUploading) {
    const params = {
      fileId: t.currentTarget.dataset.picid,
      picCategory: that.data.type,
    }
    requst_post_delPicInfo(params).then(res => {
      for (let index = 0; index < that.data.posts.length; index++) {
        const element = that.data.posts[index];
        if (element.id == t.currentTarget.dataset.picid) {
          this.data.posts.splice(index, 1)
          this.setData({
            posts: this.data.posts
          })
        }

      }

    }).catch(err => {})

  }
  },
  async uploadAll () {
  
    var that = this;
    if (this.data.ispareMoudle) {
      wx.showLoading({
        title: '上传中。。。请勿操作',
        mask: true,
      })
      var images = [];
      for (let index = 0; index < this.data.posts.length; index++) {
        const element = this.data.posts[index];
        images.push(element.path)
      }
      var params = {
        picCategory: this.data.type,
        groupId: this.data.picType,
        picList: images,
        title:  this.data.title,
        mpName:this.data.mpName,
      };
       requst_post_saveMpArticleImages(params).then(res => {
        that.setData({
          posts: []
        })
        wx.hideLoading({
          success: (res) => {},
        })
      }).catch(err => {
        wx.hideLoading({
          success: (res) => {},
        })
      })
    } else {
     var images1 = [];
     for (let index = 0; index < this.data.posts.length; index++) {
       images1.push(this.data.posts[index].path)
     }
      for (let index = 0; index < images1.length; index++) {
        wx.showLoading({
          title: '上传中。。。请勿操作',
          mask: true,
        })
        const element = images1[index];
        var params = {
          picCategory: this.data.type,
          groupId: this.data.picType,
        };
        
        await requst_uploadPic(params, element).then(res => {
          for (let index1 = 0; index1 < that.data.posts.length; index1++) {
            const element1 = that.data.posts[index1];
            if(element1.path==element){
              console.log("比对",element1.path)
              that.data.posts.splice(index1, 1)
              that.setData({
                posts: that.data.posts
              })
            }
          }
          wx.hideLoading({
            success: (res) => {},
          })
        }).catch(err => {
          console.log("失败", that.data.posts.length)
          wx.showToast({
            title: err,
          })
          wx.hideLoading({
            success: (res) => {},
          })
        })
      }
    }
  }

});